import os
import cv2
import numpy as np
import pandas as pd


def save_std_npy2csv(std_npy, target_folder, filename):
    data = np.load(std_npy)
    np.savetxt(os.path.join(target_folder, filename), data, delimiter=",")


def draw_std_area2binary(std_npy, target_folder, filename):
    data = np.load(std_npy)
    min_val = data.min()
    max_val = data.max()
    data = (data - min_val) * (255 / (max_val - min_val))
    data = data.astype(np.uint8)
    ret, data = cv2.threshold(data, 80, 255, cv2.THRESH_BINARY)
    cv2.imwrite(
        os.path.join(target_folder, filename), data)
    np.savetxt(os.path.join(target_folder, filename[:-3] + 'csv'), data, delimiter=",")


def csv2png(csv_path, target):
    """
    csv转为图像
    Args:
        csv_path:
        target:

    Returns:

    """
    with open(csv_path) as csvfile:
        image = np.loadtxt(csvfile, delimiter=",", skiprows=0)
    image.astype(np.uint8)
    cv2.imwrite(target, image)


def binary_img2npy(img_path, target):
    """
    黑白图像转为 false / true npy
    Args:
        img_path:
        target:

    Returns:

    """
    image = cv2.imread(img_path)
    image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
    zero_ind = image == 0
    max_ind = image == 255
    image[zero_ind] = True
    image[max_ind] = False
    image = image.astype(np.bool)
    np.save(target, image)


def add_up_data(npy, row, col, data, batch):
    for i in range(max(0, row - batch), row):
        npy[i][col] = data
    return npy


def add_bottom_data(npy, row, col, data, batch):
    x, y = npy.shape
    for i in range(row + 1, min(x, row + 1 + batch)):
        npy[i][col] = data
    return npy


def expand_boundary_area_csv2csv(meta_csv, target_csv, boundary=5):
    with open(meta_csv) as csvfile:
        csv = np.loadtxt(csvfile, delimiter=",", skiprows=0)
    csv.astype(np.uint8)
    x, y = csv.shape
    for i in range(x):
        for j in range(y):
            if csv[i][j] == 255:
                csv = add_up_data(csv, i, j, 255, boundary)
    for i in range(x - 1, -1, -1):
        for j in range(y - 1, -1, -1):
            if csv[i][j] == 255:
                csv = add_bottom_data(csv, i, j, 255, boundary)
    np.savetxt(target_csv, csv, fmt='%d', delimiter=",")
